'''
Created on Oct 4, 2011

@author: peterd
'''

import os, pickle

import networkx as nx


def main():
    link_repos = {'workdays_school': {}, 'workdays_noschool': {}, 'weekend': {}}
    for link_repo_type, link_repo in link_repos.iteritems():
        g = None
        if os.getcwd().find('/mhd') != -1:
            g = nx.read_gpickle('../graphs/mhdg_%s.pickle' % link_repo_type)
        else:
            g = nx.read_gpickle('graphs/mhdg_%s.pickle' % link_repo_type)
            
        for stop in g.nodes(data = True):
            print "generating %s link-repo entries for stop %d ..." % (link_repo_type, stop[0])
            links_t = []
            for link in stop[1]['links']:
                links_t.append((link['name'], link['dir'], link['stop_num']))
                
            w_xfer_links = []
            for e in g.edges_iter(stop[0], keys = True, data = True):
                if e[3]['type'] == 'w':
                    nearbyLinks = []
                    for nearbyLink in g.node[e[1]]['links']:
                        nearbyLinks.append({'name': nearbyLink['name'], 'dir': nearbyLink['dir'], 'stop_num': nearbyLink['stop_num']})
                    if nearbyLinks:
                        w_xfer_links.append({'stop_id': e[1], 'links': nearbyLinks})
                            
            for link in stop[1]['links']:
                xfer_links = []
                for link_t in links_t:
                    if link_t[0] != link['name']:
                        xfer_links.append(link_t)
                                        
                if not link_repo.has_key(link['name']):
                    link_repo[link['name']] = {}
                if not link_repo[link['name']].has_key(link['dir']):
                    link_repo[link['name']][link['dir']] = {}                 
                link_repo[link['name']][link['dir']][link['stop_num']] = {'stop_id': stop[0], 'xfer_links': xfer_links, 'w_xfer_links': w_xfer_links}
        
        if os.getcwd().find('/mhd') != -1:
            pickle.dump(link_repo, open('../graphs/link_repo_%s.pickle' % link_repo_type, 'w'))
        else:
            pickle.dump(link_repo, open('graphs/link_repo_%s.pickle' % link_repo_type, 'w'))

    print 'done'
        


if __name__ == '__main__':
    main()